﻿using System;
using System.Globalization;
using System.Windows.Forms;
using NhapXuatTon.Properties;

namespace NhapXuatTon
{
    public partial class FormChiTiet : Form
    {
        private static FormChiTiet _instance;
        private readonly FormMain _frmMain = FormMain.GetInstance();
        private int Type { set; get; }
        private String MaSanPham { set; get; }
        private readonly Clsdatabase _cls = new Clsdatabase();
        private double DonGia { set; get; }
        private double TienXuat { set; get; }
        private double LuongTon { set; get; }
        private double LuongXuat { set; get; }
        private double TienTon { set; get; }
        private double LuongNhap { set; get; }
        private double TienNhap { set; get; }

        public FormChiTiet(int type, String maSanPham)
        {
            InitializeComponent();
            Type = type;
            MaSanPham = maSanPham;
        }

        public static FormChiTiet GetInstance(int type, String maSanPham)
        {
            return _instance ?? (_instance = new FormChiTiet(type, maSanPham));
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void FormChiTiet_FormClosed(object sender, FormClosedEventArgs e)
        {
            _frmMain.btnThemMoi.Enabled = true;
            _frmMain.btnSua.Enabled = true;
            _frmMain.btnThoat.Enabled = true;
            _frmMain.btnXoa.Enabled = true;
            _instance = null;
        }

        private void FormChiTiet_Load(object sender, EventArgs e)
        {
            _frmMain.btnThemMoi.Enabled = false;
            _frmMain.btnSua.Enabled = false;
            _frmMain.btnThoat.Enabled = false;
            _frmMain.btnXoa.Enabled = false;
            dateTimePicker.Format = DateTimePickerFormat.Custom;
            dateTimePicker.CustomFormat = Resources.FormatDate;
            if (Type != 1)
            {
                LoadDbToText(MaSanPham);
                UpdateForm(MaSanPham);
                txtMaSanPham.ReadOnly = true;
                btnLuuBangChinh.Text = Resources.LuuBangChinh;
            }
        }

        private void SaveBangChinh(object sender, EventArgs e)
        {
            if (txtMaSanPham.Text == "")
            {
                MessageBox.Show(Resources.NhapMaSanPham);
                return;
            }
            if (dataGridView1.Rows.Count == 0)
            {
                MessageBox.Show(Resources.KhongCoSanPham);
                return;
            }

            //check ngay thang
            //luu vao bangchinh thang hien tai cua gridview
            //check masanpham va ngaythang trong bangchinh
            //compare voi cai thang cần lưu, nếu mã trùng và khác ngày tháng ==> add new
            //nếu khác mã => addnew
            //còn lại => udpate

            //trong truong hợp edit: nếu nhập ngày tháng lớn hơn ngày tháng của bảng chính ==> báo lỗi

            //check trung khoa           

            var getDate = dataGridView1["Ngày tháng", 0].Value.ToString();
            var date = Convert.ToDateTime(getDate).ToString("yyyy-MM-dd");    
                                
            // var date = dateTimePicker.Value.ToString("yyyy-MM-dd");
            var insert = string.Format("INSERT INTO BangChinh (DonViTinh, DonGia, LuongDauKy, " 
                                       + "TienDauKy, LuongNhap, TienNhap, LuongXuat, TienXuat, NgayThang, MaSanPham, " 
                                       + "TonCuoiKy, TienCuoiKy, VatLieu, NguyenLieu)" 
                                       + " Values (N'{0}', N'{1}', '{2}', '{2}', '{3}', '{4}', " + 
                                       "'{5}', '{6}', '{7}', '{8}', '{9}', '{10}', N'{11}', N'{12}')",
                txtDonViTinh.Text, DonGia, 0, LuongNhap, TienNhap, LuongXuat, TienXuat, date, 
                txtMaSanPham.Text, LuongTon, TienTon, txtVatLieu.Text, txtNguyenLieu.Text);

            var update = "";

            if (_cls.Kttrungkhoa(txtMaSanPham.Text, "Select MaSanPham from BangChinh"))
            {
                MessageBox.Show(Resources.SanPhamTonTai);
                return;
            }

            _cls.Thucthiketnoi(insert);
            _frmMain.LoadDbToForm();
            MessageBox.Show(Resources.ThemDuLieuThanhCong);
            Close();
        }

        private void txtTienXuat_TextChanged(object sender, EventArgs e)
        {

        }

        private void ThemMoi(object sender, EventArgs e)
        {
            //validate mandatory fie  
            if (txtMaSanPham.Text == "")
            {
                MessageBox.Show(Resources.NhapMaSanPham);
                return;
            }

            var luongXuat = "0";
            var luongNhap = "0";
            var tienNhap = "0";
            var date = dateTimePicker.Value.ToString("yyyy-MM-dd");

            if (txtLuongXuat.Text.Trim() != "")
                luongXuat = txtLuongXuat.Text.Trim().ToString(CultureInfo.InvariantCulture);
            if (txtLuongNhap.Text.Trim() != "")
                luongNhap = txtLuongNhap.Text.Trim().ToString(CultureInfo.InvariantCulture);
            if (txtTienNhap.Text.Trim() != "")
                tienNhap = txtTienNhap.Text.Trim().ToString(CultureInfo.InvariantCulture);
            
            var insert = string.Format("INSERT INTO BangChiTiet(SoHieu, NgayThang, TenSanPham, TaiKhoanDU," 
                + "DonGia, SoLuongNhap, TienNhap, SoLuongXuat, MaSanPham)" 
                + " Values (N'{0}', '{1}', N'{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}')", 
                txtSoHieu.Text, date, txtDienGiai.Text, txtDoiUng.Text, txtDonGia.Text, 
                luongNhap, tienNhap, luongXuat, txtMaSanPham.Text);

            if (MaSanPham == "")

                if (_cls.Kttrungkhoa(txtMaSanPham.Text, "Select MaSanPham from BangChinh"))
                {
                    MessageBox.Show(Resources.SanPhamTonTai);
                    return;
                }

            _cls.Thucthiketnoi(insert);
            UpdateForm(txtMaSanPham.Text);
            ResetTextBox();
            txtMaSanPham.ReadOnly = true;
        }

        private void LoadDbToText(String maSanPham)
        {
            var queryDonViTinh = "select DonViTinh from BangChinh where MaSanPham = '" + maSanPham + "'";
            var queryVatLieu = "select VatLieu from BangChinh where MaSanPham = '" + maSanPham + "'";
            var queryNguyenLieu = "select NguyenLieu from BangChinh where MaSanPham = '" + maSanPham + "'";
            txtMaSanPham.Text = MaSanPham;
            _cls.Loadtextbox(txtDonViTinh, queryDonViTinh);
            _cls.Loadtextbox(txtVatLieu, queryVatLieu);
            _cls.Loadtextbox(txtNguyenLieu, queryNguyenLieu);
        }

        private void UpdateForm(String maSanPham)
        {
            _cls.Loaddatagridview(dataGridView1,
                                  string.Format("select IDSanPham, SoHieu as 'Số hiệu', NgayThang as 'Ngày tháng', TenSanPham as 'Diễn giải', TaiKhoanDU as 'TK Đối ứng', " 
                                  + "DonGia as 'Đơn giá', SoLuongNhap as 'Số lượng nhập', TienNhap as 'Tiền nhập', SoLuongXuat as 'Số lượng xuất', MaSanPham as 'Mã sản phẩm' " 
                                  + "from BangChiTiet Where MaSanPham = '{0}'", maSanPham));

            double tongLuongXuat = 0;
            double tongLuongNhap = 0;
            double tongTienNhap = 0;

            for (var j = 0; j < dataGridView1.Rows.Count - 1; j++)
            {
                tongLuongXuat = tongLuongXuat + double.Parse(dataGridView1["Số lượng xuất", j].Value.ToString());
                tongLuongNhap = tongLuongNhap + double.Parse(dataGridView1["Số lượng nhập", j].Value.ToString());
                tongTienNhap = tongTienNhap + double.Parse(dataGridView1["Tiền nhập", j].Value.ToString());
            }

            LuongXuat = tongLuongXuat;
            LuongNhap = tongLuongNhap;
            TienNhap = tongTienNhap;

            DonGia = TienNhap > 0 && LuongNhap > 0 ? Math.Round(TienNhap / LuongNhap) : 0;
            TienXuat = DonGia * LuongXuat;
            TienXuat = Math.Round(TienXuat, 2);
            LuongTon = tongLuongNhap - tongLuongXuat;
            TienTon = Math.Round(DonGia*LuongTon, 2);


            txtTongLuongXuat.Text = tongLuongXuat.ToString(CultureInfo.InvariantCulture);
            txtLuongTon.Text = LuongTon.ToString(CultureInfo.InvariantCulture);
            txtTienTon.Text = TienTon.ToString(CultureInfo.InvariantCulture);
            txtTienXuat.Text = TienXuat.ToString(CultureInfo.InvariantCulture);
        }

        private void txtLuongNhap_TextChanged(object sender, EventArgs e)
        {
            var donGia = txtDonGia.Text;
            var soLuongNhap = txtLuongNhap.Text;
            double thanhTienNhap = 0;
            if (txtDonGia.Text.Trim() != "" && txtLuongNhap.Text.Trim() != "")
                thanhTienNhap = Convert.ToDouble(donGia)*Convert.ToInt32(soLuongNhap);
            txtTienNhap.Text = Convert.ToDouble(thanhTienNhap).ToString(CultureInfo.InvariantCulture);
        }

        private void txtDonGia_TextChanged(object sender, EventArgs e)
        {
            var donGia = txtDonGia.Text;
            var soLuongNhap = txtLuongNhap.Text;
            double thanhTienNhap = 0;
            if (txtDonGia.Text.Trim() != "" && txtLuongNhap.Text.Trim() != "")
                thanhTienNhap = Convert.ToDouble(donGia)*Convert.ToInt32(soLuongNhap);
            txtTienNhap.Text = Convert.ToDouble(thanhTienNhap).ToString(CultureInfo.InvariantCulture);
        }

        private void ResetTextBox()
        {
            txtSoHieu.Text = string.Empty;
            txtDienGiai.Text = string.Empty;
            txtDonViTinh.Text = string.Empty;
            txtDoiUng.Text = string.Empty;
            txtDonGia.Text = string.Empty;
            txtLuongNhap.Text = string.Empty;
            txtLuongXuat.Text = string.Empty;
            txtTienNhap.Text = string.Empty;
            txtGhiChu.Text = string.Empty;
        }       
    }

}